package com.xioaming.coupon.serialization;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.xioaming.coupon.entity.Coupon;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author jxbai
 * @desc 优惠券实体类自定义序列化器
 * @date 2020/6/9
 */
public class CouponSerialize extends JsonSerializer<Coupon> {

    @Override
    public void serialize(Coupon coupon, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException {
        //开始序列化
        generator.writeStartObject();

        generator.writeStringField("id", coupon.getId().toString());
        generator.writeStringField("templateId", coupon.getTemplateId().toString());
        generator.writeObjectField("userId", coupon.getUserId().toString());
        generator.writeObjectField("couponCode", coupon.getCouponCode());
        generator.writeObjectField("assignTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(coupon.getAssignTime()));
        generator.writeObjectField("name", coupon.getTemplateSDK().getName());
        generator.writeObjectField("logo", coupon.getTemplateSDK().getLogo());
        generator.writeObjectField("description", coupon.getTemplateSDK().getDescription());
        generator.writeObjectField("expiration", coupon.getTemplateSDK().getRule().getExpiration());
        generator.writeObjectField("discount", coupon.getTemplateSDK().getRule().getDiscount());
        generator.writeObjectField("usage", coupon.getTemplateSDK().getRule().getUsage());

        //结束序列化
        generator.writeEndObject();
    }
}
